using System.Configuration;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;

namespace Ipmce.RemoteVoting.Common.Tools.Wcf.Unity
{
	public class UnityContainerFactory
	{
		/// <summary>
		/// Configuration section name for Unity.
		/// </summary>
		private const string UnityConfigurationSectionName = "unity";

		/// <summary>
		/// Creates an instance of <see cref="Microsoft.Practices.Unity.UnityContainer"/> from configuration using the provided container name.
		/// </summary>
		/// <param name="containerName">Container name to configure.  If containerName is null or empty, the default container is configured.</param>
		/// <returns>Created and configured <see cref="Microsoft.Practices.Unity.UnityContainer"/>.</returns>
		public static IUnityContainer Create(string containerName)
		{
			IUnityContainer unityContainer = new UnityContainer();
			var section = ConfigurationManager.GetSection(
				UnityConfigurationSectionName) as UnityConfigurationSection;
			if (section != null)
			{
				if (string.IsNullOrEmpty(containerName))
				{
					section.Configure(unityContainer);
				}
				else
				{
					section.Configure(unityContainer, containerName);
				}
			}

			return unityContainer;
		}

		/// <summary>
		/// Creates an instance of <see cref="Microsoft.Practices.Unity.UnityContainer"/> from configuration.
		/// </summary>
		/// <returns>Created and configured <see cref="Microsoft.Practices.Unity.UnityContainer"/>.</returns>
		public static IUnityContainer Create()
		{
			return Create(null);
		}
	}
}